package com.ddtech.business.bank.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ddtech.business.bank.bo.*;
import com.ddtech.business.bank.entity.QuestionBank;
import com.ddtech.business.bank.entity.QuestionBankQuestion;
import com.ddtech.business.bank.entity.QuestionBankQuestionOption;
import com.ddtech.business.bank.mapper.QuestionBankMapper;
import com.ddtech.business.bank.query.QuestionBankQuery;
import com.ddtech.business.common.BaseService;
import com.ddtech.business.constant.BusinessEnum;
import com.ddtech.business.practice.mapper.PracticeUserRecordMapper;
import com.ddtech.exception.BadRequestException;
import com.ddtech.exception.BizPreconditions;
import com.ddtech.framework.system.model.SysSpecialty;
import com.ddtech.framework.system.service.SysSpecialtyService;
import com.ddtech.utils.FileUtil;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 题库服务类
 *
 * @author bin
 * @date 2023/2/11 15:32
 */
@Service
public class QuestionBankService extends BaseService<QuestionBankMapper, QuestionBank> {

    @Autowired
    private QuestionBankQuestionService questionBankQuestionService;

    @Autowired
    private QuestionBankQuestionOptionService questionBankQuestionOptionService;
    @Resource
    private QuestionBankMapper questionBankMapper;
    @Resource
    private PracticeUserRecordMapper recordMapper;
    @Autowired
    private SysSpecialtyService sysSpecialtyService;

    @Value("${file.path}")
    private String filePath;

    public Object getQueBankList(String keyWords, Integer type, int page, int pageSize) {
        IPage pageInfo = new Page(page+1, pageSize);
        IPage<Map<String, Object>> queBankList = questionBankMapper.getQueBankList(pageInfo, keyWords, type);
        return PageUtil.toPage(queBankList.getRecords(), queBankList.getTotal());
    }

    /**
     * description:查询专项检测题库
     * @param:  * @param questionBankQuery
     * @date: 2023-12-18
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    public Object getQueBankListNoPage(QuestionBankQuery questionBankQuery) {
        List<Map<String, Object>> queBankList = questionBankMapper.getQueBankListNoPage(questionBankQuery);
        return queBankList;
    }

    /**
     * description:根据题库ID，查询可用标签
     * @param:  * @param questionBankQuery
     * @date: 2023-12-18
     * @return: java.lang.Object
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    public Object getQueBankListSource(QuestionBankQuery questionBankQuery) {
        List<Map<String, Object>> queBankList = questionBankMapper.getQueBankListSource(questionBankQuery);
        return queBankList;
    }

    public Object bankListTotal(QuestionBankQuery questionBankQuery) {
        if(questionBankQuery.getSpecialtyId()!=null && !"0".equals(questionBankQuery.getSpecialtyId())){
            Set<SysSpecialty> subSpecialty = sysSpecialtyService.getSubSpecialty(questionBankQuery.getSpecialtyId());
            if(CollUtil.isNotEmpty(subSpecialty)){
                List<String> ids = subSpecialty.stream().map(SysSpecialty::getId).collect(Collectors.toList());
                questionBankQuery.setSpecialtyIds(ids);
            }
        }
        IPage<Map<String, Object>> page = questionBankMapper.bankListTotal(questionBankQuery.populatePage(), questionBankQuery);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }


    public void doSaveOrUpdate(QuestionBank questionBank) {
        questionBank.init();
        questionBank.setCreateBy(SecurityUtils.getName());
        this.saveOrUpdate(questionBank);
    }


    public void delete(String id) {
        QuestionBank questionBank = this.getById(id);
        BizPreconditions.check(questionBank == null, BusinessEnum.OPERATE_ERROR.getMsg());
        questionBank.baseDelete();
        this.saveOrUpdate(questionBank);
    }


    /**
     * description: 据题库id查询某个题库中所有的题目及答案
     *
     * @param questionDesc
     * @param optionType
     * @param page
     * @param size
     * @param: * @param examId
     * @date: 2023-04-28
     * @return: java.util.List<com.ddtech.business.bank.bo.BankQueAndOpt>
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    public Map<String, Object> getListPageData(String examId, String questionDesc, String optionType, int page, int size) {
        IPage pageInfo = new Page(page+1, size);
        Map<String, Object> queList = questionBankQuestionService.questionBankQuestionPageList(examId, questionDesc, optionType, pageInfo);
        if (queList.get("totalElements").toString().equals("0")) {
            return queList;
        }
        ArrayList<QuestionBankQuestion> ls = (ArrayList) queList.get("content");
        List<BankQueAndOpt> returnList = new ArrayList<>();
        getQueAndOption(ls, returnList, examId);
        queList.put("content", returnList);
        return queList;
    }

    /**
     * 根据题库id查询某个题库中所有的题目及答案
     *
     * @param examId
     * @return
     */
    public List<BankQueAndOpt> getListData(String examId) {
        List<QuestionBankQuestion> queList = questionBankQuestionService.questionBankQuestionList(examId);
        if (CollectionUtils.isEmpty(queList)) {
            return null;
        }
        List<BankQueAndOpt> returnList = new ArrayList<>();
        getQueAndOption(queList, returnList, examId);
        return returnList;
    }

    public void addOrUpdateQueAndOpt(AddBankQueAndOpt addBankQueAndOpt) {
        List<BankQueAndOpt> list = addBankQueAndOpt.getLists();
        for (BankQueAndOpt bankQueAndOpt : list) {
            if (StringUtils.isBlank(bankQueAndOpt.getId())) {
                bankQueAndOpt.setId(IdWorker.getIdStr());
                QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
                BeanUtils.copyProperties(bankQueAndOpt, questionBankQuestion);
                questionBankQuestion.init();
                questionBankQuestion.setCreateTime(LocalDateTime.now());
                questionBankQuestionService.doSaveOrUpdate(questionBankQuestion);
                List<QuestionBankQuestionOption> optList = bankQueAndOpt.getLists();
                int orderNum=1;
                for (QuestionBankQuestionOption questionBankQuestionOption : optList) {
                    questionBankQuestionOption.setId(IdWorker.getIdStr());
                    questionBankQuestionOption.setBankId(bankQueAndOpt.getBankId());
                    questionBankQuestionOption.init();
                    questionBankQuestionOption.setOrderNum(Long.valueOf(orderNum++));
                    questionBankQuestionOption.setCreateTime(LocalDateTime.now());
                    questionBankQuestionOption.setQuestionId(bankQueAndOpt.getId());
                    questionBankQuestionOptionService.doSaveOrUpdate(questionBankQuestionOption);
                }
            } else {
                QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
                BeanUtils.copyProperties(bankQueAndOpt, questionBankQuestion);
                questionBankQuestion.init();
                questionBankQuestionService.saveOrUpdate(questionBankQuestion);
                List<QuestionBankQuestionOption> optList = bankQueAndOpt.getLists();
                int orderNum=1;
                for (QuestionBankQuestionOption questionBankQuestionOption : optList) {
                    questionBankQuestionOption.setOrderNum(Long.valueOf(orderNum++));
                    if (StringUtils.isBlank(questionBankQuestionOption.getId())) {
                        questionBankQuestionOption.setId(IdWorker.getIdStr());
                        questionBankQuestionOption.setBankId(bankQueAndOpt.getBankId());
                        questionBankQuestionOption.setQuestionId(bankQueAndOpt.getId());
                        questionBankQuestionOption.init();
                        questionBankQuestionOption.setCreateTime(LocalDateTime.now());
                    }
                    questionBankQuestionOptionService.doSaveOrUpdate(questionBankQuestionOption);
                }
            }
        }
    }

    /**
     * 删除题库、题目及题目选项
     *
     * @param examId
     */
    public void deleteBank(String examId) {
        this.delete(examId);
        questionBankQuestionService.batchDeleteQuestionBankQuestion(examId);
        questionBankQuestionOptionService.batchDeleteQuestionBankQuestionOption(examId);
    }

    /***
     * description: 删除题目及题目选项
     * @param:  * @param questionId
     * @date: 2023-04-28
     * @return: void
     * @version v1.0
     * @author:wei_zhang(xiao)
     */
    public void deleteBankQuesAndOption(String questionId) {
        questionBankQuestionService.removeById(questionId);
        questionBankQuestionOptionService.batchDeleteQuestionBankQuestionOptionByQuestionId(questionId);
    }


    public Integer getQueCount(List<String> ids) {
        QueryWrapper<QuestionBankQuestion> questionBankQueryWrapper = questionBankQuestionService.newValidQueryWrapper();
        questionBankQueryWrapper.in(QuestionBankQuestion.BANK_ID, ids);
        return questionBankQuestionService.count(questionBankQueryWrapper);
    }

    @Autowired
    private QuestionBankQuestionOptionService optionService;

    @Transactional(rollbackFor = Exception.class)
    public QuestionBank importQue(String bankId, MultipartFile file) {
        QuestionBank questionBank = null;
        if ("0".equals(bankId)) {
            questionBank = new QuestionBank();
            questionBank.init();
            questionBank.setType(2);
            questionBank.setBankName(file.getOriginalFilename());
            this.saveOrUpdate(questionBank);
            bankId = questionBank.getId();
        } else {
            questionBank = this.getById(bankId);
        }
        List<BankQuestionBO> list;
        try {
            list = EasyExcel.read(file.getInputStream()).head(BankQuestionBO.class).sheet().headRowNumber(1).doReadSync();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequestException("导入失败！");
        }

        BizPreconditions.check(list.isEmpty(), "题目不能为空");
        int questionNum = 0;
        for (BankQuestionBO importBankQuestionDto : list) {
            //题目
            String question = importBankQuestionDto.getQuestion();
            //分值
            Double score = importBankQuestionDto.getScore();
            //是否多选
            String optionType = importBankQuestionDto.getOptionType();
            //正确选项
            String isTrue = importBankQuestionDto.getIsTrue();
            if (question == null || score == null || optionType == null || isTrue == null) {
                continue;
            }
            Integer optionTypeValue = "是".equals(optionType) ? 1 : 0;
            QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
            String questionId = IdWorker.getIdStr();
            questionBankQuestion.init();
            questionBankQuestion.setId(questionId);

            questionBankQuestion.setBankId(bankId);
            questionBankQuestion.setQuestionNum(questionNum++);
            questionBankQuestion.setQuestionDesc(question);
            questionBankQuestion.setOptionType(optionTypeValue);
            questionBankQuestion.setScore(score);
            List<QuestionBankQuestionOption> bankQuestionOptions = buildQuestionOptionInfo(bankId, questionId, importBankQuestionDto);
            questionBankQuestionService.saveOrUpdate(questionBankQuestion);
            optionService.saveBatch(bankQuestionOptions);
        }
        return questionBank;
    }

    private List<QuestionBankQuestionOption> buildQuestionOptionInfo(String examId, String questionId, BankQuestionBO importBankQuestionDto) {
        String isTrue = importBankQuestionDto.getIsTrue();
        List<QuestionBankQuestionOption> bankQuestionOptions = new ArrayList<>();
        String optionA = importBankQuestionDto.getOptionA();
        buildQuestionOption(optionA, bankQuestionOptions, examId, questionId, 1L, isTrue.contains("A") ? 1 : 0);
        String optionB = importBankQuestionDto.getOptionB();
        buildQuestionOption(optionB, bankQuestionOptions, examId, questionId, 2L, isTrue.contains("B") ? 1 : 0);
        String optionC = importBankQuestionDto.getOptionC();
        buildQuestionOption(optionC, bankQuestionOptions, examId, questionId, 3L, isTrue.contains("C") ? 1 : 0);
        String optionD = importBankQuestionDto.getOptionD();
        buildQuestionOption(optionD, bankQuestionOptions, examId, questionId, 4L, isTrue.contains("D") ? 1 : 0);
        String optionE = importBankQuestionDto.getOptionE();
        buildQuestionOption(optionE, bankQuestionOptions, examId, questionId, 5L, isTrue.contains("E") ? 1 : 0);
        String optionF = importBankQuestionDto.getOptionF();
        buildQuestionOption(optionF, bankQuestionOptions, examId, questionId, 6L, isTrue.contains("F") ? 1 : 0);
        String optionG = importBankQuestionDto.getOptionG();
        buildQuestionOption(optionG, bankQuestionOptions, examId, questionId, 7L, isTrue.contains("G") ? 1 : 0);
        String optionH = importBankQuestionDto.getOptionH();
        buildQuestionOption(optionH, bankQuestionOptions, examId, questionId, 8L, isTrue.contains("H") ? 1 : 0);
        String optionI = importBankQuestionDto.getOptionI();
        buildQuestionOption(optionI, bankQuestionOptions, examId, questionId, 9L, isTrue.contains("I") ? 1 : 0);
        String optionJ = importBankQuestionDto.getOptionJ();
        buildQuestionOption(optionJ, bankQuestionOptions, examId, questionId, 10L, isTrue.contains("J") ? 1 : 0);
        return bankQuestionOptions;
    }

    private void buildQuestionOption(String option,
                                     List<QuestionBankQuestionOption> questionBankQuestionOptions, String bankId,
                                     String questionId,
                                     Long orderNum,
                                     Integer isTrue) {
        if (StringUtils.isBlank(option)) {
            return;
        }
        QuestionBankQuestionOption questionBankQuestionOption = new QuestionBankQuestionOption();
        questionBankQuestionOption.init();
        questionBankQuestionOption.setOrderNum(orderNum);
        questionBankQuestionOption.setBankId(bankId);
        questionBankQuestionOption.setAnswerDesc(option);
        questionBankQuestionOption.setQuestionId(questionId);
        questionBankQuestionOption.setIsTrue(isTrue);
        questionBankQuestionOptions.add(questionBankQuestionOption);
    }

    public void exportQue(String examId, HttpServletResponse response) {
        List<BankQueAndOpt> queList = getListData(examId);
        BizPreconditions.check(queList == null || queList.isEmpty(), "导出题目不存在");
        List<BankQuestionBO> bankQuestions = new ArrayList<>();
        for (BankQueAndOpt bankQueAndOpt : queList) {
            BankQuestionBO bankQuestionBO = new BankQuestionBO();
            List<QuestionBankQuestionOption> lists = bankQueAndOpt.getLists();
            List<QuestionBankQuestionOption> orderCollect = lists.stream().sorted(Comparator.comparing(QuestionBankQuestionOption::getOrderNum)).collect(Collectors.toList());
            AtomicLong ord = new AtomicLong(0);
            orderCollect.stream().map(item -> {
                item.setOrderNum(ord.incrementAndGet());
                return item;
            }).collect(Collectors.toList());
            bankQuestionBO.setQuestion(bankQueAndOpt.getQuestionDesc());
            bankQuestionBO.setScore(bankQueAndOpt.getScore());
            bankQuestionBO.setOptionType(1 == bankQueAndOpt.getOptionType() ? "是" : "否");
            bankQuestionBO.setIsTrue("");
            buildTrueOption(orderCollect, bankQuestionBO);
            bankQuestions.add(bankQuestionBO);
        }
        try {
            String fileName = "题目.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            // 下载文件能正常显示中文
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            EasyExcel.write(response.getOutputStream(), BankQuestionBO.class).sheet("题目").doWrite(bankQuestions);
        } catch (IOException e) {
            e.printStackTrace();
            BizPreconditions.check(true, "导出失败");
        }
    }

    private void buildTrueOption(List<QuestionBankQuestionOption> lists, BankQuestionBO bankQuestionBO) {
        for (QuestionBankQuestionOption questionBankQuestionOption : lists) {
            transformLetter(questionBankQuestionOption, bankQuestionBO);
        }
    }

    private void transformLetter(QuestionBankQuestionOption questionBankQuestionOption, BankQuestionBO bankQuestionBO) {
        Long longOrd = questionBankQuestionOption.getOrderNum();
        String answerDesc = questionBankQuestionOption.getAnswerDesc();
        Integer optionIsTrue = questionBankQuestionOption.getIsTrue();
        String isTrue = bankQuestionBO.getIsTrue();
        final Integer opTrue = 1;
        if (longOrd == 1) {
            bankQuestionBO.setOptionA(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("A"));
            }
        }
        if (longOrd == 2) {
            bankQuestionBO.setOptionB(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("B"));
            }
        }
        if (longOrd == 3) {
            bankQuestionBO.setOptionC(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("C"));
            }
        }
        if (longOrd == 4) {
            bankQuestionBO.setOptionD(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("D"));
            }
        }
        if (longOrd == 5) {
            bankQuestionBO.setOptionE(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("E"));
            }
        }
        if (longOrd == 6) {
            bankQuestionBO.setOptionF(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("F"));
            }
        }
        if (longOrd == 7) {
            bankQuestionBO.setOptionG(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("G"));
            }
        }
        if (longOrd == 8) {
            bankQuestionBO.setOptionH(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("H"));
            }
        }
        if (longOrd == 9) {
            bankQuestionBO.setOptionI(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("I"));
            }
        }
        if (longOrd == 10) {
            bankQuestionBO.setOptionJ(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("J"));
            }
        }
    }

    public void downLoadQueTel(HttpServletResponse response) {
        //String path = FileUtil.convertTemplatePath("tpl" + File.separator + "仓库消防题目导入模板.xlsx");
        String path=filePath+"tpl" + File.separator + "仓库消防题目导入模板.xlsx";
        FileUtil.download(response, new File(path), "仓库消防题目导入模板.xlsx");
    }

    public Object getManyError(IPage pageableRequest, String questionName) {
        IPage page = recordMapper.getManyError(pageableRequest, questionName);
        List<String> questionIds = page.getRecords();
        if (CollUtil.isNotEmpty(questionIds)) {
            LambdaQueryWrapper<QuestionBankQuestion> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(QuestionBankQuestion::getId, questionIds);
            List<QuestionBankQuestion> list = questionBankQuestionService.list(queryWrapper);
            List<BankQueAndOpt> bankQueAndOpts = new ArrayList<>();
            getQueAndOption(list, bankQueAndOpts, null);
            page.setRecords(bankQueAndOpts);
        }
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    private void getQueAndOption(List<QuestionBankQuestion> list, List<BankQueAndOpt> bankQueAndOpts, String bankId) {
        for (QuestionBankQuestion questionBankQuestion : list) {
            BankQueAndOpt bankQueAndOpt = new BankQueAndOpt(questionBankQuestion);
            List<QuestionBankQuestionOption> questionBankQuestionOptions = questionBankQuestionOptionService.queryoptList(bankId, questionBankQuestion.getId());
            bankQueAndOpt.setLists(questionBankQuestionOptions);
            bankQueAndOpts.add(bankQueAndOpt);
        }
    }

    public Object bankSearch(IPage pageableRequest, String questionName) {
        LambdaQueryWrapper<QuestionBankQuestion> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(questionName)) {
            queryWrapper.like(QuestionBankQuestion::getQuestionDesc, questionName);
        }
        IPage page = questionBankQuestionService.page(pageableRequest, queryWrapper);
        List<BankQueAndOpt> bankQueAndOpts = new ArrayList<>();
        List<QuestionBankQuestion> list = page.getRecords();
        getQueAndOption(list, bankQueAndOpts, null);
        page.setRecords(bankQueAndOpts);
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Transactional(rollbackFor = Exception.class)
    public Object importQueV2(String bankId, String majorId, MultipartFile file) {
        QuestionBank questionBank;
        if ("0".equals(bankId)) {
            questionBank = new QuestionBank();
            questionBank.init();
            questionBank.setType(2);
            questionBank.setBankName(file.getOriginalFilename());
            this.saveOrUpdate(questionBank);
            bankId = questionBank.getId();
        } else {
            questionBank = this.getById(bankId);
        }
        List<BankQuestionV2BO> list;
        try {
            list = EasyExcel.read(file.getInputStream()).head(BankQuestionV2BO.class).sheet().headRowNumber(2).doReadSync();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BadRequestException("导入失败！");
        }
        BizPreconditions.check(list.isEmpty(), "题目不能为空");

        int questionNum = 0;
        for (BankQuestionV2BO importBankQuestionDto : list) {
            //题目
            String question = importBankQuestionDto.getQuestion();
            //题型
            String questionType = importBankQuestionDto.getQuestionType();
            if (question == null) {
                continue;
            }
            QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
            String questionId = IdWorker.getIdStr();
            questionBankQuestion.init();
            questionBankQuestion.setId(questionId);
            questionBankQuestion.setBankId(bankId);
            questionBankQuestion.setQuestionNum(questionNum++);
            questionBankQuestion.setQuestionDesc(question);
            questionBankQuestion.setOptionType(getQuestionType(questionType));
//            SysSpecialty specialty = this.getMajorId(importBankQuestionDto.getMajorType(),majorId);
//            if(specialty!=null){
//                questionBankQuestion.setMajorId(specialty.getId());
//                questionBankQuestion.setMajorType(specialty.getLabel());
//            }
            questionBankQuestion.setBasis(importBankQuestionDto.getBasis());
            questionBankQuestion.setScore(importBankQuestionDto.getScore());
            questionBankQuestion.setKeywords(importBankQuestionDto.getKeywords());
            List<QuestionBankQuestionOption> bankQuestionOptions = buildQuestionOptionInfoV2(bankId, questionId, importBankQuestionDto);
            questionBankQuestionService.saveOrUpdate(questionBankQuestion);
            if (CollUtil.isNotEmpty(bankQuestionOptions)) {
                optionService.saveBatch(bankQuestionOptions);
            }
        }
        return questionBank;
    }

    private SysSpecialty getMajorId(String majorType,String majorId) {
        SysSpecialty specialty = sysSpecialtyService.getSysSpecialtyByName(majorType);
        if(specialty==null && StringUtils.isNotBlank(majorId)){
            specialty = sysSpecialtyService.getById(majorId);
        }
        return specialty;

    }

    private List<QuestionBankQuestionOption> buildQuestionOptionInfoV2(String examId, String questionId, BankQuestionV2BO bankQuestionV2BO) {
        String isTrue = bankQuestionV2BO.getIsTrue();
        List<QuestionBankQuestionOption> bankQuestionOptions = new ArrayList<>();
        if (StringUtils.isNotBlank(isTrue)) {
            String optionA = bankQuestionV2BO.getOptionA();
            buildQuestionOption(optionA, bankQuestionOptions, examId, questionId, 1L, isTrue.contains("A") ? 1 : 0);
            String optionB = bankQuestionV2BO.getOptionB();
            buildQuestionOption(optionB, bankQuestionOptions, examId, questionId, 2L, isTrue.contains("B") ? 1 : 0);
            String optionC = bankQuestionV2BO.getOptionC();
            buildQuestionOption(optionC, bankQuestionOptions, examId, questionId, 3L, isTrue.contains("C") ? 1 : 0);
            String optionD = bankQuestionV2BO.getOptionD();
            buildQuestionOption(optionD, bankQuestionOptions, examId, questionId, 4L, isTrue.contains("D") ? 1 : 0);
            String optionE = bankQuestionV2BO.getOptionE();
            buildQuestionOption(optionE, bankQuestionOptions, examId, questionId, 5L, isTrue.contains("E") ? 1 : 0);
            String optionF = bankQuestionV2BO.getOptionF();
            buildQuestionOption(optionF, bankQuestionOptions, examId, questionId, 6L, isTrue.contains("F") ? 1 : 0);
            String optionG = bankQuestionV2BO.getOptionG();
            buildQuestionOption(optionG, bankQuestionOptions, examId, questionId, 7L, isTrue.contains("G") ? 1 : 0);
            String optionH = bankQuestionV2BO.getOptionH();
            buildQuestionOption(optionH, bankQuestionOptions, examId, questionId, 8L, isTrue.contains("H") ? 1 : 0);
        }
        return bankQuestionOptions;
    }

    private Integer getQuestionType(String questionType) {
        if (StringUtils.isBlank(questionType)) {
            return 3;
        }
        questionType = questionType.trim();
        switch (questionType) {
            case "单选题":
                return 0;
            case "多选题":
                return 1;
            case "判断题":
                return 2;
            case "案例题":
                return 3;
            default:
                return -1;
        }

    }




    public void exportQueV2(String bankId, HttpServletResponse response) {
        List<BankQueAndOpt> queList = getListData(bankId);
        QuestionBank questionBank = this.getById(bankId);
        BizPreconditions.check(queList == null || queList.isEmpty(), "导出题目不存在");
        List<BankQuestionV2BO> bankQuestions = new ArrayList<>();
        int i=1;
        for (BankQueAndOpt bankQueAndOpt : queList) {
            BankQuestionV2BO bankQuestionV2BO = new BankQuestionV2BO();
            List<QuestionBankQuestionOption> lists = bankQueAndOpt.getLists();
            List<QuestionBankQuestionOption> orderCollect = lists.stream().sorted(Comparator.comparing(QuestionBankQuestionOption::getOrderNum)).collect(Collectors.toList());
            AtomicLong ord = new AtomicLong(0);
            orderCollect.stream().map(item -> {
                item.setOrderNum(ord.incrementAndGet());
                return item;
            }).collect(Collectors.toList());
            bankQuestionV2BO.setNumber(String.valueOf(i++));
            bankQuestionV2BO.setQuestion(bankQueAndOpt.getQuestionDesc());
            bankQuestionV2BO.setQuestionType(getQuestionType(bankQueAndOpt.getOptionType()));
            //bankQuestionV2BO.setMajorType(bankQueAndOpt.getMajorType());
            bankQuestionV2BO.setBasis(bankQueAndOpt.getBasis());//试题解析
            bankQuestionV2BO.setScore(bankQueAndOpt.getScore());//分值
            bankQuestionV2BO.setKeywords(bankQueAndOpt.getKeywords());//标签
            bankQuestionV2BO.setIsTrue("");
            buildTrueOptionV2(orderCollect, bankQuestionV2BO);
            bankQuestions.add(bankQuestionV2BO);
        }
        try {
            String fileName = "题目.xlsx";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            // 下载文件能正常显示中文
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            EasyExcel.write(response.getOutputStream(), BankQuestionV2BO.class)
                    .registerWriteHandler(new CustomerTitleHandler(questionBank.getBankName()))
                    .sheet()
                    .doWrite(bankQuestions);
        } catch (IOException e) {
            e.printStackTrace();
            BizPreconditions.check(true, "导出失败");
        }
    }

    private String getQuestionType(Integer questionType) {
        switch (questionType) {
            case 0:
                return "单选题";
            case 1:
                return "多选题";
            case 2:
                return "判断题";
            case 3:
                return "案例题";
        }
        return "案例题";

    }

    private void buildTrueOptionV2(List<QuestionBankQuestionOption> lists, BankQuestionV2BO bankQuestionBO) {
        for (QuestionBankQuestionOption questionBankQuestionOption : lists) {
            transformLetterV2(questionBankQuestionOption, bankQuestionBO);
        }
    }

    private void transformLetterV2(QuestionBankQuestionOption questionBankQuestionOption, BankQuestionV2BO bankQuestionBO) {
        Long longOrd = questionBankQuestionOption.getOrderNum();
        String answerDesc = questionBankQuestionOption.getAnswerDesc();
        Integer optionIsTrue = questionBankQuestionOption.getIsTrue();
        String isTrue = bankQuestionBO.getIsTrue();
        final Integer opTrue = 1;
        if (longOrd == 1) {
            bankQuestionBO.setOptionA(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("A"));
            }
        }
        if (longOrd == 2) {
            bankQuestionBO.setOptionB(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("B"));
            }
        }
        if (longOrd == 3) {
            bankQuestionBO.setOptionC(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("C"));
            }
        }
        if (longOrd == 4) {
            bankQuestionBO.setOptionD(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("D"));
            }
        }
        if (longOrd == 5) {
            bankQuestionBO.setOptionE(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("E"));
            }
        }
        if (longOrd == 6) {
            bankQuestionBO.setOptionF(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("F"));
            }
        }
        if (longOrd == 7) {
            bankQuestionBO.setOptionG(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("G"));
            }
        }
        if (longOrd == 8) {
            bankQuestionBO.setOptionH(answerDesc);
            if (opTrue.equals(optionIsTrue)) {
                bankQuestionBO.setIsTrue(isTrue.concat("H"));
            }
        }
    }

}
